<?php

namespace app\admin\controller;

use think\Db;

class Ulog extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [];
        if (!empty($param['device_id'])) {
            $where['device_id'] = ['eq', $param['device_id']];
        }

        $order = 'ulog_id desc';
        $res = model('Ulog')->listData($where, $order, $param['page'], $param['limit']);

        $this->assign('list', $res['list']);
        $this->assign('total', $res['total']);
        $this->assign('page', $res['page']);
        $this->assign('limit', $res['limit']);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('param', $param);

        $this->assign('title', '日志管理');
        return $this->fetch('admin@ulog/index');
    }

    public function vodindex()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [];
        if (!empty($param['device_id'])) {
            $where['uh.device_id'] = $param['device_id'];
        }
        if (!empty($param['app_id'])) {
            $where['uh.app_id'] = $param['app_id'];
        }
        $order = 'uh.time_added desc';
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;
        $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;
        $total = \db('user_history')->alias('uh')->join('vod v', 'v.vod_id=uh.vod_id', 'LEFT')->where($where)->count();
        $list = \db('user_history')->alias('uh')->join('vod v', 'v.vod_id=uh.vod_id', 'LEFT')->where($where)->order($order)->limit($limit_str)->select();
        $applists = \db('banben')->column('app_id,appname as app_name');
        $this->assign('applists', $applists);
        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('limit', $limit);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('param', $param);

        $this->assign('title', '影视访问记录');
        return $this->fetch('admin@ulog/vodindex');
    }

    public function zhiboindex()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [];
        if (!empty($param['device_id'])) {
            $where['uh.device_id'] = $param['device_id'];
        }
        if (!empty($param['app_id'])) {
            $where['uh.app_id'] = $param['app_id'];
        }
        $order = 'uh.time_added desc';
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;
        $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;
        $total = \n2db('zhibo_history')->alias('uh')->where($where)->count();
        $list = \n2db('zhibo_history')->alias('uh')->where($where)->order($order)->limit($limit_str)->select();
        $applists = \db('banben')->column('app_id,appname as app_name');
        $this->assign('applists', $applists);
        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('limit', $limit);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('param', $param);

        $this->assign('title', '影视访问记录');
        return $this->fetch('admin@ulog/zhiboindex');
    }

    public function vodstatistics()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = ['v.vod_id' => ['>', 0]];
        if (empty($param['setType'])) {
            if (empty($param['start'])) {
                $param['start'] = strtotime('today');
            } else {
                $param['start'] = strtotime(urldecode(urldecode($param['start'])));
            }

            if (empty($param['end'])) {
                $param['end'] = time();
            } else {
                $param['end'] = strtotime(urldecode(urldecode($param['end'])));
            }
        } else {
            switch ($param['setType']) {
                case 'today':
                    $param['start'] = strtotime('today');
                    $param['end'] = time();
                    break;
                case 'yesterday':
                    $param['start'] = strtotime('yesterday');
                    $param['end'] = strtotime('today');
                    break;
                case 'week':
                    $param['start'] = strtotime('-1 week', strtotime('today'));
                    $param['end'] = time();
                    break;
                default:
                    unset($param['setType']);
                    break;
            }
        }
        if ($param['end'] <= $param['start']) {
            $this->error('结束时间不能早于开始时间');
        }


        $where['uh.time_added'] = ['between', [$param['start'], $param['end']]];
        if (!empty($param['app_id'])) {
            $where['uh.app_id'] = $param['app_id'];
        }

        $order = 'count(distinct device_id) desc';
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;
        $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;
        $total = \db('user_history')->alias('uh')->join('vod v', 'v.vod_id=uh.vod_id', 'LEFT')->where($where)->group('uh.vod_id')->count();
        $list = \db('user_history')->alias('uh')->join('vod v', 'v.vod_id=uh.vod_id', 'LEFT')->fieldRaw('v.vod_id,v.vod_name,id,count(1) as num,count(distinct device_id) as device_num')->group('uh.vod_id')->where($where)->orderRaw($order)->limit($limit_str)->select();
//        dump(\db('user_history')->getLastSql());
        $applists = \db('banben')->column('app_id,appname as app_name');
        $this->assign('applists', $applists);
        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('limit', $limit);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $param['start'] = date('Y-m-d H:i:s', $param['start']);
        $param['end'] = date('Y-m-d H:i:s', $param['end']);
//        dump($param);
        $this->assign('param', $param);
        $this->assign('title', '影视访问统计');
        return $this->fetch('admin@ulog/vodstatistics');
    }

    public function devicetatistics()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [];
        if (empty($param['setType'])) {
            if (empty($param['start'])) {
                $param['start'] = strtotime('today');
            } else {
                $param['start'] = strtotime(urldecode(urldecode($param['start'])));
            }

            if (empty($param['end'])) {
                $param['end'] = strtotime('tomorrow') - 1;
            } else {
                $param['end'] = strtotime(urldecode(urldecode($param['end'])));
            }
        } else {
            switch ($param['setType']) {
                case 'today':
                    $param['start'] = strtotime('today');
                    $param['end'] = strtotime('tomorrow') - 1;
                    break;
                case 'yesterday':
                    $param['start'] = strtotime('yesterday');
                    $param['end'] = strtotime('today');
                    break;
                case 'week':
                    $param['start'] = strtotime('-1 week', strtotime('today'));
                    $param['end'] = strtotime('tomorrow') - 1;
                    break;
                default:
                    unset($param['setType']);
                    break;
            }
        }

        if ($param['end'] <= $param['start']) {
            $this->error('结束时间不能早于开始时间');
        }
        $where['s.time_updated'] = ['between', [$param['start'], $param['end']]];

        if (!empty($param['app_id'])) {
            $where['s.app_id'] = $param['app_id'];
        }
        $order = 'sum(s.times) desc,s.time_updated desc';
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;
        $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;
        $timeStart = $param['start'] - 1;
        $timeEnd = $param['end'];
        $sql = "SELECT COUNT(1) AS num,sum(ios) AS iosSum,sum(android) AS androidSum,sum(is_new) AS is_new,SUM(iosTimes) AS iosTimes,SUM(androidTimes) AS androidTimes FROM (SELECT device_id,max(is_new) AS is_new,CASE WHEN system_type='ios' THEN 1 ELSE 0 END AS ios,CASE WHEN system_type='android' THEN 1 ELSE 0 END AS android,sum(CASE WHEN system_type='ios' THEN times ELSE 0 END) AS iosTimes,sum(CASE WHEN system_type='android' THEN times ELSE 0 END) AS androidTimes FROM mac_state WHERE ( time_added BETWEEN " . $timeStart . " AND " . $timeEnd;

        if (isset($where['s.app_id'])) {
            $sql .= " and app_id = '" . $where['s.app_id'] . "'";
        }
        $sql .= " ) GROUP BY app_id,device_id) AS tt";
//        dump($sql);
        $countDevice = db('state')->query($sql);
        $tongji = $countDevice[0];

        $total = \db('state')->alias('s')->join('device d','d.device_id = s.device_id and d.app_id = s.app_id','LEFT')->where($where)->group('s.app_id,s.device_id')->count();

//        dump($tongji);
        $list = \db('state')->alias('s')->fieldRaw('s.device_id,min(s.time_added) as time_added,max(s.time_updated) as time_updated,max(s.app_version) as app_version,s.app_id,s.app_name,s.system_type,s.device_name,s.x,s.y,s.sheng,s.shi,sum(s.times) as num,d.points,d.time_expired')->group('s.app_id,s.device_id')->join('device d','d.device_id = s.device_id and d.app_id = s.app_id','LEFT')->where($where)->orderRaw($order)->limit($limit_str)->select();
//        dump(\db('user_history')->getLastSql());
        $applists = \db('banben')->column('app_id,appname as app_name');
        $this->assign('applists', $applists);

        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('limit', $limit);
        $this->assign($tongji);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $param['start'] = date('Y-m-d H:i:s', $param['start']);
        $param['end'] = date('Y-m-d H:i:s', $param['end']);
//        dump($param);
        $this->assign('param', $param);
        $this->assign('title', '设备在线统计');
        return $this->fetch('admin@ulog/devicetatistics');
    }

    public function zhibostatistics()
    {
        $param = input();
        $where = [];
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        if (empty($param['setType'])) {
            if (empty($param['start'])) {
                $param['start'] = strtotime('today');
            } else {
                $param['start'] = strtotime(urldecode($param['start']));
            }

            if (empty($param['end'])) {
                $param['end'] = time();
            } else {
                $param['end'] = strtotime(urldecode($param['end']));
            }
        } else {
            switch ($param['setType']) {
                case 'today':
                    $param['start'] = strtotime('today');
                    $param['end'] = time();
                    break;
                case 'yesterday':
                    $param['start'] = strtotime('yesterday');
                    $param['end'] = strtotime('today');
                    break;
                case 'week':
                    $param['start'] = strtotime('-1 week', strtotime('today'));
                    $param['end'] = time();
                    break;
                default:
                    unset($param['setType']);
                    break;
            }
        }
        if ($param['end'] <= $param['start']) {
            $this->error('结束时间不能早于开始时间');
        }
        $timeStart = $param['start'] - 1;
        $timeEnd = $param['end'];

        if (!empty($param['app_id'])) {
            $where['zh.app_id'] = $param['app_id'];
        }

        $sql = "SELECT COUNT(1) AS num,sum(ios) AS iosSum,sum(android) AS androidSum FROM (
SELECT device_id, CASE WHEN system_type='ios' THEN 1 ELSE 0 END AS ios,CASE WHEN system_type='android' THEN 1 ELSE 0 END AS android FROM mac_zhibo_history as zh WHERE (time_added BETWEEN " . $timeStart . " AND " . $timeEnd . " )";
        if (isset($where['zh.app_id'])) {
            $sql .= ' and zh.app_id = "' . $where['zh.app_id'] . '"';
        }

        $sql .= " GROUP BY device_id) AS tt";
//        dump($sql);exit;
        $countDevice = n2db('zhibo')->query($sql);
        $tongji = $countDevice[0];
//        dump($tongji);
        $this->assign($tongji);


        $where['zh.time_added'] = ['between', [$param['start'], $param['end']]];
        $order = 'count(distinct device_id) desc';
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;
        $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;
        $total = \n2db('zhibo_history')->alias('zh')->join('zhibo_type t', 't.id=zh.type_id', 'LEFT')->where($where)->group('zh.zhibo_id')->count();
        $list = \n2db('zhibo_history')->alias('zh')->join('zhibo_type t', 't.id=zh.type_id', 'LEFT')->fieldRaw('t.id as type_id,t.name as type_name,zh.zhibo_name,zh.zhibo_id,zh.zhibo_qiudui,zh.zhibo_time,count(1) as num,count(distinct device_id) as device_num')->group('zh.zhibo_id')->where($where)->orderRaw($order)->limit($limit_str)->select();
//        dump(\db('user_history')->getLastSql());
        $applists = \db('banben')->column('app_id,appname as app_name');
        $this->assign('applists', $applists);

        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('limit', $limit);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $param['start'] = date('Y-m-d H:i:s', $param['start']);
        $param['end'] = date('Y-m-d H:i:s', $param['end']);
//        dump($param);
        $this->assign('param', $param);
        $this->assign('title', '直播访问统计');
        return $this->fetch('admin@ulog/zhibostatistics');
    }

    public function del()
    {
        $param = input();
        $ids = $param['ids'];
        $all = $param['all'];
        if (!empty($ids)) {
            $where = [];
            $where['ulog_id'] = ['in', $ids];
            if ($all == 1) {
                $where['ulog_id'] = ['gt', 0];
            }
            $res = model('Ulog')->delData($where);
            if ($res['code'] > 1) {
                return $this->error($res['msg']);
            }
            return $this->success($res['msg']);
        }
        return $this->error('参数错误');
    }


    public function devices()
    {
        $param = input();
        $keywords = $param['keywords'];
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [];
        if (empty($param['setType'])) {
            if (empty($param['start'])) {
                $param['start'] = strtotime('today');
            } else {
                $param['start'] = strtotime(urldecode(urldecode($param['start'])));
            }

            if (empty($param['end'])) {
                $param['end'] = strtotime('tomorrow') - 1;
            } else {
                $param['end'] = strtotime(urldecode(urldecode($param['end'])));
            }
        } else {
            switch ($param['setType']) {
                case 'today':
                    $param['start'] = strtotime('today');
                    $param['end'] = strtotime('tomorrow') - 1;
                    break;
                case 'yesterday':
                    $param['start'] = strtotime('yesterday');
                    $param['end'] = strtotime('today');
                    break;
                case 'week':
                    $param['start'] = strtotime('-1 week', strtotime('today'));
                    $param['end'] = time();
                    break;
                default:
                    unset($param['setType']);
                    break;
            }
        }

        if ($param['end'] <= $param['start']) {
            $this->error('结束时间不能早于开始时间');
        }
        $where['time_added'] = ['between', [$param['start'], $param['end']]];

        if (!empty($param['app_id'])) {
            $where['app_id'] = $param['app_id'];
        }
        if (!empty($param['keywords'])) {
            $where['device_id|device_name'] = ['like', '%' . $param['keywords'] . '%'];
        }

        $order = 'time_updated desc, time_added desc';
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;
        $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;

//        $tongjiSql = "SELECT SUM(CASE WHEN system_type='ios' THEN 1 ELSE 0 END) AS iosNum,SUM(CASE WHEN system_type='android' THEN 1 ELSE 0 END) AS android FROM mac_device where time_updated between ".$param['start'] .' and '.$param['end'];

        //得到ios今日数据
        $newIosNum = \db('device')->where($where)->where('system_type', 'ios')->count();
        $newAndroidNum = \db('device')->where($where)->where('system_type', 'android')->count();

        $applists = \db('banben')->column('app_id,appname as app_name');


        $total = \db('device')->where($where)->count();
        $list = \db('device')->where($where)->orderRaw($order)->limit($limit_str)->select();
//        dump(\db('user_history')->getLastSql());
//exit;
        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('limit', $limit);
        $this->assign('newIosNum', $newIosNum);
        $this->assign('newAndroidNum', $newAndroidNum);
        $this->assign('applists', $applists);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $param['start'] = date('Y-m-d H:i:s', $param['start']);
        $param['end'] = date('Y-m-d H:i:s', $param['end']);
//        dump($param);
        $this->assign('param', $param);
        $this->assign('title', '设备管理');
        return $this->fetch('admin@ulog/devices');
    }

    public function devicelog()
    {
        $appId = input('app_id');
        $deviceId = input('device_id');
        $param = input();
        $param['page'] = '{page}';
        $param['limit'] = '{limit}';

        $deviceInfo = \db('device')->order('time_updated', 'desc')->where('app_id', $appId)->where('device_id', $deviceId)->find();

        $list = \db('openadlog')->where('app_id', $appId)->where('device_id', $deviceId)->order('ctime', 'desc')->paginate(20);
//        dump(\db('openadlog')->getLastSql());

        $this->assign('list', $list->items());
        $this->assign('total', $list->total());
        $this->assign('page', $list->currentPage());
        $this->assign('limit', $list->listRows());
        $this->assign('deviceInfo', $deviceInfo);
        $this->assign('param', $param);
        return $this->fetch('admin@ulog/devicelog');
    }

    public function devicedate()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [];
        $param['date'] = trim(urldecode(urldecode($param['date'])));
        $param['date'] = strtotime($param['date']);
        if ($param['date'] === false) {
            $param['date'] = date('Y-m-d', strtotime('yesterday'));
        } else {
            $param['date'] = date('Y-m-d', $param['date']);
        }


        $where['dd.date'] = $param['date'];

        if (!empty($param['app_id'])) {
            $where['dd.app_id'] = $param['app_id'];
        }
        $order = isset($param['order'])?$param['order']:'';
        if(empty($order)) {
            $order = '(dd.kaiping_num + dd.quanping_num + dd.jili_num) desc,(dd.vod_num + dd.zhibo_num) desc';
        }else{
            if(!in_array($order,['kaiping_num','quanping_num','jili_num'])){
                $this->error('排序条件有问题！');
            }
            $order =" ".$order." desc";
        }
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;
        $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;


        $applists = \db('banben')->column('app_id,appname as app_name');


        $total = \db('device_date')->alias('dd')->where($where)
            ->count();
        $list = \db('device_date')->alias('dd')->join('device d', 'd.app_id=dd.app_id and d.device_id = dd.device_id', 'LEFT')
            ->fieldRaw("dd.*,d.is_need_updated")
            ->where($where)->orderRaw($order)->limit($limit_str)->select();
//        dump($list);
//        dump(\db('user_history')->getLastSql());
//exit;
        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('limit', $limit);
        $this->assign('applists', $applists);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
//        dump($param);
        $this->assign('param', $param);
        $this->assign('title', '设备数据统计');
        return $this->fetch('admin@ulog/devicedate');
    }

    public function updatedevice()
    {
        $input = input();
        $count = \db('openadlog')->where('app_id', $input['app_id'])->where('device_id', $input['device_id'])->whereTime('ctime','today')->whereIn('adtype',[1,2,3])->count()?:0;
        $changeStatus = true;
        $appinfo = \db('banben')->cache('app_banben',5)->where('app_id',$input['app_id'])->find();
        if(empty($appinfo)){
            $changeStatus = false;
        }else {
            $guanggao = \db('guanggaonew')->cache('guanggao_new', 5)->where('keyname', $appinfo['keyname'])->find();
            if (empty($guanggao) || $guanggao['allstatus'] == 0) {
                $changeStatus = false;
            }
        }
        if($count<1 && $changeStatus) {
            $return = \db('device')->where('app_id', $input['app_id'])->where('device_id', $input['device_id'])->update([
                'is_need_updated' => $input['settype'] != 0 ? 1 : 0
            ]);
        }else{
            $return = false;
        }
        if ($return !== false) {
            $this->success('操作成功！', null, \db('device')->getLastSql());
        } else {
            $this->error('操作失败！');
        }
    }


    public function uniqueDeviceList()
    {
        $param = input();
//        dump($param);exit;
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [];
        if (empty($param['setType'])) {
            if (empty($param['start'])) {
                $param['start'] = strtotime('today');
            } else {
                $param['start'] = strtotime(urldecode(urldecode($param['start'])));
            }

            if (empty($param['end'])) {
                $param['end'] = strtotime('tomorrow') - 1;
            } else {
                $param['end'] = strtotime(urldecode(urldecode($param['end'])));
            }
        } else {
            switch ($param['setType']) {
                case 'today':
                    $param['start'] = strtotime('today');
                    $param['end'] = strtotime('tomorrow') - 1;
                    break;
                case 'yesterday':
                    $param['start'] = strtotime('yesterday');
                    $param['end'] = strtotime('today');
                    break;
                case 'week':
                    $param['start'] = strtotime('-1 week', strtotime('today'));
                    $param['end'] = time();
                    break;
                default:
                    unset($param['setType']);
                    break;
            }
        }

        $where['time_added'] = ['between', [$param['start'], $param['end']]];

        if (!empty($param['app_id'])) {
            $where['app_id'] = $param['app_id'];
        }

        if ($param['vod_id'] > 0) {
            $where['vod_id'] = $param['vod_id'];
            $vodInfo = \db('vod')->fieldRaw('vod_id,vod_name')->where('vod_id', $param['vod_id'])->find();
            $list = \db('user_history')->fieldRaw("app_id,app_name,device_id,device_name")->group('app_id,device_id')->where($where)->paginate($param['limit']);
            $this->assign('vodInfo', $vodInfo);

        } else if ($param['zhibo_id'] > 0) {
            $where['zhibo_id'] = $param['zhibo_id'];
            $zhiboInfo = n2db('zhibo_history')->field('zhibo_id,zhibo_name,zhibo_qiudui')->where('zhibo_id', $param['zhibo_id'])->order('id', 'desc')->find();
            $list = \n2db('zhibo_history')->fieldRaw("app_id,app_name,device_id,device_name")->group('app_id,device_id')->where($where)->paginate($param['limit']);
            $this->assign('zhiboInfo', $zhiboInfo);
        } else {
            return '访问有误';
        }

        $this->assign('list', $list->items());
        $this->assign('total', $list->total());
        $this->assign('page', $list->currentPage());
        $this->assign('limit', $list->listRows());

        $applists = \db('banben')->column('app_id,appname as app_name');
        $this->assign('applists', $applists);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $param['start'] = date('Y-m-d H:i:s', $param['start']);
        $param['end'] = date('Y-m-d H:i:s', $param['end']);
//        dump($param);
        $this->assign('param', $param);
        return $this->fetch('admin@ulog/uniquedevicelist');
    }

    public function deviceLogList()
    {
        $param = input();
//        dump($param);exit;
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [];
        if (empty($param['setType'])) {
            if (empty($param['start'])) {
                $param['start'] = strtotime('today');
            } else {
                $param['start'] = strtotime(urldecode(urldecode($param['start'])));
            }

            if (empty($param['end'])) {
                $param['end'] = strtotime('tomorrow') - 1;
            } else {
                $param['end'] = strtotime(urldecode(urldecode($param['end'])));
            }
        } else {
            switch ($param['setType']) {
                case 'today':
                    $param['start'] = strtotime('today');
                    $param['end'] = strtotime('tomorrow') - 1;
                    break;
                case 'yesterday':
                    $param['start'] = strtotime('yesterday');
                    $param['end'] = strtotime('today');
                    break;
                case 'week':
                    $param['start'] = strtotime('-1 week', strtotime('today'));
                    $param['end'] = time();
                    break;
                default:
                    unset($param['setType']);
                    break;
            }
        }

        $where['time_added'] = ['between', [$param['start'], $param['end']]];

        if (!empty($param['app_id'])) {
            $where['app_id'] = $param['app_id'];
        }

        if ($param['vod_id'] > 0) {
            $where['vod_id'] = $param['vod_id'];
            $vodInfo = \db('vod')->fieldRaw('vod_id,vod_name')->where('vod_id', $param['vod_id'])->find();
            $list = \db('user_history')->fieldRaw("app_id,app_name,device_id,device_name,time_added")->order('time_added', 'desc')->where($where)->paginate($param['limit']);
            $this->assign('vodInfo', $vodInfo);

        } else if ($param['zhibo_id'] > 0) {
            $where['zhibo_id'] = $param['zhibo_id'];
            $zhiboInfo = n2db('zhibo_history')->field('zhibo_id,zhibo_name,zhibo_qiudui')->where('zhibo_id', $param['zhibo_id'])->order('id', 'desc')->find();
            $list = \n2db('zhibo_history')->fieldRaw("app_id,app_name,device_id,device_name,time_added")->order('time_added', 'desc')->where($where)->paginate($param['limit']);
            $this->assign('zhiboInfo', $zhiboInfo);
        } else {
            return '访问有误';
        }

        $this->assign('list', $list->items());
        $this->assign('total', $list->total());
        $this->assign('page', $list->currentPage());
        $this->assign('limit', $list->listRows());

        $applists = \db('banben')->column('app_id,appname as app_name');
        $this->assign('applists', $applists);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $param['start'] = date('Y-m-d H:i:s', $param['start']);
        $param['end'] = date('Y-m-d H:i:s', $param['end']);
//        dump($param);
        $this->assign('param', $param);
        return $this->fetch('admin@ulog/deviceloglist');
    }

    public function needUpdateDevices()
    {
        $param = input();
        $keywords = $param['keywords'];
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [
            'is_need_updated' => 1
        ];
        if (!empty($param['app_id'])) {
            $where['app_id'] = $param['app_id'];
        }
        if (!empty($param['keywords'])) {
            $where['device_id|device_name'] = ['like', '%' . $param['keywords'] . '%'];
        }

        $order = 'time_updated desc, time_added desc';
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;
        $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;

//        $tongjiSql = "SELECT SUM(CASE WHEN system_type='ios' THEN 1 ELSE 0 END) AS iosNum,SUM(CASE WHEN system_type='android' THEN 1 ELSE 0 END) AS android FROM mac_device where time_updated between ".$param['start'] .' and '.$param['end'];
        $applists = \db('banben')->column('app_id,appname as app_name');


        $total = \db('device')->where($where)->count();
        $list = \db('device')->where($where)->orderRaw($order)->limit($limit_str)->select();
//        dump(\db('user_history')->getLastSql());
//exit;
        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('limit', $limit);
        $this->assign('applists', $applists);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $param['start'] = date('Y-m-d H:i:s', $param['start']);
        $param['end'] = date('Y-m-d H:i:s', $param['end']);
//        dump($param);
        $this->assign('param', $param);
        $this->assign('title', '设备管理');
        return $this->fetch('admin@ulog/needupdatedevices');
    }


    public function keyidevices()
    {
        $param = input();
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $where = [];


        $order = 'count(dd.date) desc,sum(dd.kaiping_num + dd.quanping_num + dd.jili_num) asc,max(dd.sign_days) desc,sum(dd.vod_num + dd.zhibo_num) desc';
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;

        //得到没有开启广告的appid keyname
        $keynames = \db('guanggaonew')->where('allstatus',0)->column('keyname');

        $appids = \db('banben')->whereIn('keyname',$keynames)->column('app_id');
        if (!empty($param['app_id']) && !in_array($param['app_id'],$appids)) {
            $where['dd.app_id'] = $param['app_id'];
        }else{
            $where['dd.app_id']=['not in',$appids];
        }
//        dump($tongji);
//        dump($where);
        $list = \db('device_date')->alias('dd')
            ->join('device d', 'd.device_id = dd.device_id and dd.app_id = d.app_id', 'left')
            ->fieldRaw('dd.app_id,d.time_expired,d.points,d.is_need_updated,dd.app_name,dd.device_id,dd.device_name,count(dd.id) as login_days,max(dd.sign_days) as sign_days,sum(dd.kaiping_num) as kaiping_num,sum(dd.quanping_num) as guanping_num,sum(dd.jili_num) as jili_num,sum(dd.vod_num) as vod_num,sum(dd.zhibo_num) as zhibo_num')
            ->where($where)
            ->where('d.is_need_updated', 0)
            ->where(function ($query) {
                $query->where('d.time_expired', 0)->whereOr('d.time_expired', '<', strtotime('today'));
            })
            ->whereTime('dd.date', '- 3 days')->group('dd.app_id,dd.device_id')
            ->having('sum(dd.jili_num + dd.quanping_num + dd.kaiping_num)=0 and sum(dd.vod_num + dd.zhibo_num)>0')
            ->orderRaw($order)->paginate($param['limit']);
//        dump(\db('user_history')->getLastSql());

        $applists = \db('banben')->whereNotIn('app_id',$appids)->column('app_id,appname as app_name');
        $this->assign('applists', $applists);

        $this->assign('list', $list->items());
        $this->assign('total', $list->total());
        $this->assign('page', $list->currentPage());
        $this->assign('limit', $list->listRows());

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
//        dump($param);
        $this->assign('param', $param);
        $this->assign('title', '设备访问统计信息');
        return $this->fetch('admin@ulog/keyidevices');
    }

    public function batchSetUpdate()
    {
        $ids = input('ids/a');
        if (empty($ids)) {
            $this->error('数据有误！');
        }
        try {
            foreach ($ids as $device) {
                $device = explode('$$$', $device);
                $device = [
                    'app_id' => $device[0],
                    'device_id' => $device[1],
                ];
                //检查openadlog今日是否有广告
                $count = \db('openadlog')->where('app_id', $device['app_id'])->where('device_id', $device['device_id'])->whereTime('ctime','today')->whereIn('adtype',[1,2,3])->count()?:0;
                $changeStatus = true;
                $appinfo = \db('banben')->cache('app_banben',5)->where('app_id',$device['app_id'])->find();
                if(empty($appinfo)){
                    $changeStatus = false;
                }else {
                    $guanggao = \db('guanggaonew')->cache('guanggao_new', 5)->where('keyname', $appinfo['keyname'])->find();
                    if (empty($guanggao) || $guanggao['allstatus'] == 0) {
                        $changeStatus = false;
                    }
                }
                if($count<1 && $changeStatus) {
                    $return = \db('device')->where('app_id', $device['app_id'])->where('device_id', $device['device_id'])->update([
                        'is_need_updated' => 1
                    ]);
                }
            }
            $msg = 'success';
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            $this->error($msg);
        }
        $this->success($msg);
    }
}
